package org.callisto.handlers;

import java.sql.ResultSet;

import org.callisto.DbLib;
import org.callisto.model.Event;
import org.callisto.model.Keyboard;

public class DBOutputHandler extends KeyboardObserver {
	
	Keyboard keyboard;
	static int sessionId;
	
	public DBOutputHandler(Keyboard keyboard) throws Exception {
		super(keyboard);
		System.out.println("[DB output handler]");
		this.keyboard = keyboard;
	}

	public void handleEvent(Event event) throws Exception {
		if (event.getMillis() == 0) {
			String sql = "INSERT INTO session (info) VALUES ('" + System.getenv() + "');";
			DbLib.executeUpdate(sql);
			ResultSet rs=DbLib.query("SELECT MAX(session_id) FROM session");
			rs.next();
			sessionId=rs.getInt(1);
			System.out.println("Session #" + sessionId + " created");
		}
		String sql = "INSERT INTO history (session_id,agent,source_tstmp,millis,note,status,pressure,delay) " + 
		" VALUES (" + sessionId + ",1,'" + event.getTstamp() + "'," + event.getMillis() + "," + event.getNote() + 
		"," + event.getStatus().getMidiStatusCode() + "," + event.getPressure() + "," + event.getDelay() + ");";
		DbLib.executeUpdate(sql);
	}	
}